package com.atguigu.gulimall.auth.service.impl;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.service.IRegisterService;
import com.atguigu.gulimall.auth.vo.UserRegistVO;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/9 15:53 周一
 * @description :
 */
@Service
@AllArgsConstructor
public class RegisterServiceImpl implements IRegisterService {

    private final StringRedisTemplate redisTemplate;

    private final MemberFeignService memberFeignService;

    @Override
    public String regist(UserRegistVO userRegistVO, BindingResult result, RedirectAttributes redirectAttributes) {
        // TODO 重定向携带啊数据 利用session原理 将数据放在session中 只要调到下一个页面
        //  取出这个数据之后 session里面的数据就会删掉
        // TODO 分布式下session问题
        if (result.hasErrors()) {

            Map<String, String> errors = result.getFieldErrors()
                    .stream()
                    .collect(Collectors.toMap(FieldError::getField,
                            v -> Objects.toString(v.getDefaultMessage())
                    ));

            // RedirectAttributes 模拟重定向携带数据
            redirectAttributes.addFlashAttribute("errors", errors);


            // Request method 'POST' not supported 由于forward:reg导致的 所以直接转到reg就好了

            // 校验出错 转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 1. 校验验证码
        String code = userRegistVO.getCode();
        String phone = userRegistVO.getPhone();

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String redisKey = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String phoneCode = opsForValue.get(redisKey);
        if (Func.isNotEmpty(phoneCode)) {
            phoneCode = phoneCode.split("_")[0];
            if (code.equals(phoneCode)) {
                // 验证码通过
                // 删除验证码 令牌机制
                redisTemplate.delete(redisKey);
                // 真正注册 调用远程服务进行注册
                R r = memberFeignService.register(userRegistVO);
                if (r.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }
                Map<String, String> errors = new HashMap<>(1);
                errors.put("code", Objects.toString(r.get("msg")));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            Map<String, String> errors = new HashMap<>(1);
            errors.put("code", "验证码错误");

            // RedirectAttributes 模拟重定向携带数据
            redirectAttributes.addFlashAttribute("errors", errors);

            return "redirect:http://auth.gulimall.com/reg.html";
        }
        Map<String, String> errors = new HashMap<>(1);
        errors.put("code", "验证码错误");

        // RedirectAttributes 模拟重定向携带数据
        redirectAttributes.addFlashAttribute("errors", errors);

        return "redirect:http://auth.gulimall.com/reg.html";
    }

}
